package com.fms.common.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
public class RedisUtils {
    private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    private static RedisTemplate<String, Object> redisTemplate;

    @Resource
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        RedisUtils.redisTemplate = redisTemplate;
    }

    public static Long getCurrentUserId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("Authorization");

            if (token == null || !token.startsWith("Bearer ")) {
                logger.error("Token格式错误: token为空或不是Bearer token");
                throw new RuntimeException("无效的token格式");
            }

            try {
                token = token.substring(7); // 移除"Bearer "前缀
                Object userId = redisTemplate.opsForValue().get("user_id:" + token);
                if (userId != null) {
                    return Long.parseLong(userId.toString());
                }
                logger.error("Token无效或已过期");
                throw new RuntimeException("token无效或已过期");
            } catch (Exception e) {
                logger.error("获取用户ID失败: {}", e.getMessage());
                throw new RuntimeException("获取用户ID失败: " + e.getMessage());
            }
        }
        logger.error("未获取到请求上下文");
        throw new RuntimeException("未获取到当前登录用户");
    }
}